import React, { FC, ReactNode, memo, useEffect } from 'react'

interface Iprops {
  children?: ReactNode
}
declare global {
  interface Window {
    CozeWebSDK: any
  }
}

const Agent: FC<Iprops> = () => {
  useEffect(() => {
    // 1️⃣ 动态加载 Coze SDK 脚本
    const script = document.createElement('script')
    script.src =
      'https://lf-cdn.coze.cn/obj/unpkg/flow-platform/chat-app-sdk/1.2.0-beta.10/libs/cn/index.js'
    script.async = true
    script.onload = () => {
      console.log('✅ Coze SDK 加载完成')

      // 2️⃣ 初始化 WebChatClient

      const client = new window.CozeWebSDK.WebChatClient({
        config: {
          bot_id: '7561420672098926638' // ✅ 换成你自己的 bot_id
        },
        componentProps: {
          title: '智能分诊助手' // 聊天窗口标题
        },
        auth: {
          type: 'token',
          token:
            'pat_3uyfvzpqxeQPLWrc3ojpOo0N23zbjcNcMamdX87Jdq86xvXukblmCid0DTjWpAzw', // ✅ 你的 token
          onRefreshToken: function () {
            return 'pat_3uyfvzpqxeQPLWrc3ojpOo0N23zbjcNcMamdX87Jdq86xvXukblmCid0DTjWpAzw' // ✅ token 过期时重新获取逻辑（简单写死）
          }
        },
        ui: {
          base: {
            layout: 'mobile'
          }
        }
      })

      console.log('✅ Coze WebChatClient 初始化完成', client)
    }

    document.body.appendChild(script)

    return () => {
      document.body.removeChild(script)
    }
  }, [])

  return (
    <div style={{ padding: '20px' }}>
      <h2>🧠 智能分诊助手</h2>
      <p>加载完成后，你会在页面右下角看到聊天浮窗。</p>
    </div>
  )
}

export default memo(Agent)
